<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/6/22
 * Time: 16:36
 */

namespace Weixin\Service;


use Common\Common\Service;
use Weixin\Component\Weixin\WeixinComponent;
use Weixin\Exception\WeixinException;
use Weixin\Request\Weixin\UpdateSubscribeRequest;
use Weixin\Response\UpdateSubscribeResponse;

class UpdateSubscribeService implements Service
{
    public function run(UpdateSubscribeRequest $request = null)
    {
        if ($request->issetOpenId() == false)
            throw new WeixinException(10001);

        $openid = $request->getOpenId();
        $subscribe = $request->getSubscribe();
        $component = new WeixinComponent();
        $response = new UpdateSubscribeResponse();
        try {
            if ($subscribe == true) {
                $result = $component->subscribe($openid);
            } else {
                $result = $component->unsubscribe($openid);
            }
            if (!$result) {
                $response->setItIsNull();
            }
        } catch (WeixinException $e) {
            throw new WeixinException($e->getMessage(), $e->getCode());
        }
        return $response;
    }
}